var actionController = new function(){
	
	var   _$
		, _$event
		, _$name
		, _$duration
		, _$sound
		, _$repeat
		, _$type
		, _$moveX
		, _$moveY
		, _$angle
		, _$scaleX
		, _$scaleY
		, _$texture
		, _$toboObject
		, _$toboAction
		, _$enableToboObject
		, _$launchScene
		, _$changeMusic
		, _$changeMusicTitle
		, _$stopObject
		, _$stopAction
		, _$dropObject
		, _$dropAction
		, _$highlightObject
		, _$highlightAction
		, _$indexChange		
		, _$stateChange
		, _$playAction
		, _$msg
		, _idSq
	;

	var _isSpawn = false
	  , _spawnName
	;
	
	this.spawnContainer = {};
	
	var _TEMPLATES = {
			FRAME: '<div class="tr-frame-elem">' + 
						'<input class="frame-action k-textbox" type="text" size="40" style="width:200px"/>' + 
						'<a class="remove-button" title="Eliminar frame"><img src="/img/minus.png"></a>' +
					'</div>'
		  , SPAWN:  '<div class="tr-frame-elem">' + 
						'<input class="frame-action k-textbox" type="text" size="40" style="width:200px" disabled />' + 
						'<a class="remove-spawn-button" title="Eliminar acción"><img src="/img/minus.png"></a>' +
					'</div>'
	}
	
	var _objectDataSource = new kendo.data.DataSource();
	
	var _editAction = false;
	
	function _init(){
		
		_$ = $('#new-action-window');
		_$.kendoWindow({
			  width: "600px"
			, height: "450px"
			, title: "Añade una acción al objeto"
			, modal: true
			, visible: false
			, draggable: false
			, resizable: false
		});
		
		_$event = $('#action-event')
			.kendoDropDownList({})
			.data("kendoDropDownList");
		
		_$name = $('#action-name');
		_$duration = $("#action-duration").kendoNumericTextBox({
			format: "#.#",
			decimals: 1,
			step: 0.1,
			format: "#.#",
			min: 0
		}).data("kendoNumericTextBox");
		_$repeat = $('#action-repeat').kendoNumericTextBox({
			decimals: 0,
			step: 1,
			format: "#",
			value: 0, 
			min: -1
		}).data("kendoNumericTextBox");
		_$sound = $("#action-sound");
		_$sound.kendoUpload({
        	async: {
                saveUrl: "/upload",
                autoUpload: true
            },
            showFileList: false,
            multiple: false,
            success: function(data) {uploadSoundComplete(data, _$soundTitle)},
            error: function(data) {uploadSoundComplete(data, _$soundTitle)},
            localization: {
            	select: "Seleccionar"
            }
		});
		_$soundTitle = $("#action-sound-title");
		_$type = $('#action-type')
			.kendoDropDownList({
				change: _changeType
			})
			.data("kendoDropDownList");
		
		//Configuración del tipo de acción
		_$moveX = $("#move-x").kendoNumericTextBox({
			format: "#px",
            min: -2000,
            max: 2000,
            step: 1,
            value: 0
		}).data("kendoNumericTextBox");
		_$moveY = $("#move-y").kendoNumericTextBox({
			format: "#px",
            min: -2000,
            max: 2000,
            step: 1,
            value: 0
		}).data("kendoNumericTextBox");
		_$angle = $("#angle").kendoNumericTextBox({
            format: "#º",
            decimals: 0,
            min: -360,
            max: 360,
            step: 1,
            value: 0
		}).data("kendoNumericTextBox");
		_$scaleX = $("#scale-x").kendoNumericTextBox({
			format: "#.#",
            decimals: 1,
            min: 0.1,
            max: 10,
            step: 0.1,
            value: 1
		}).data("kendoNumericTextBox");
		_$scaleY = $("#scale-y").kendoNumericTextBox({
			format: "#.#",
			decimals: 1,
            min: 0.1,
            max: 10,
            step: 0.1,
            value: 1
		}).data("kendoNumericTextBox");
		
		_$texture = $('#texture');
		
		_$toboObject = $('#tobo-object').kendoDropDownList({
			dataTextField: "name",
		    dataValueField: "name",
		    dataSource: _objectDataSource
		}).data("kendoDropDownList");
		
		_$toboAction = $('#tobo-action');
		
		_$enableToboObject = $('#enable-tobo-object').kendoDropDownList({
			dataTextField: "name",
		    dataValueField: "name",
		    dataSource: _objectDataSource
		}).data("kendoDropDownList");
		
		_$launchScene = $('#launch-scene');
		_$changeMusic = $('#change-music');
		_$changeMusicTitle = $('#change-music-title');
		_$changeMusic.kendoUpload({
        	async: {
                saveUrl: "/upload",
                autoUpload: true
            },
            showFileList: false,
            multiple: false,
            success: function(data) {uploadSoundComplete(data, _$changeMusicTitle)},
            error: function(data) {uploadSoundComplete(data, _$changeMusicTitle)},
            localization: {
            	select: "Seleccionar"
            }
		});
		
		_$stopObject = $('#stop-object').kendoDropDownList({
			dataTextField: "name",
		    dataValueField: "name",
		    dataSource: _objectDataSource
		}).data("kendoDropDownList");
		
		_$stopAction = $('#stop-action');
		
		_$dropObject = $('#drop-object').kendoDropDownList({
			dataTextField: "name",
		    dataValueField: "name",
		    dataSource: _objectDataSource
		}).data("kendoDropDownList");
		
		_$dropAction = $('#drop-action');	
		
		_$highlightObject = $('#highlight-object').kendoDropDownList({
			dataTextField: "name",
		    dataValueField: "name",
		    dataSource: _objectDataSource
		}).data("kendoDropDownList");
		
		_$highlightAction = $('#highlight-action');	
		_$stateChange = $('#state-change');
		
		_$indexChange = $('#index-change').kendoNumericTextBox({
			decimals: 0,
            value: 0,
            step: 1,
            format: '#'
		}).data("kendoNumericTextBox");
		
		_$playAction = $('#play-action');
		
		_$msg = $('#action-msg');
		
		_$actionList = $('#action-list');
		
		$('#cancel-action-btn').click(function(){
			if (_isSpawn){
				closeWindow4Spawn();
			}
			else {
				_closeWindow();	
			}
			
		})
		$('#accept-action-btn').click(function(){
			if (_check()){
				
				_addAction();
			}
		})
		
		$('#new-action-window').on('click', '.add-button', function(){
			_addTR(this);
		})
		
		$('#new-action-window').on('click', '.remove-button', function(){
			_removeTR(this);
		})
		
		$('#new-action-window').on('click', '.remove-spawn-button', function(){
			_removeSpawn(this);
			_removeTR(this);
		})
		
		
		_reset();
	}
	
	
	function uploadSoundComplete(data, title){
		
		var extension = data.files[0].extension;
		
		if (extension != ".mp3" && extension != ".ogg" && extension != ".wav"){
			
			title.text('Fichero de audio no válido.');
		}
		else {
			
			var fileName = data.files[0].name;
	    	window.console.log('Audio subido correctamente: ' + fileName);
	    	title.text(fileName);
		}
	}
	
	
	function _removeTR(e){
		
		$(e).parent().remove();
	}
	
	
	function _addTR(e){
		
		var   wrapper = $(e).parent().parent()
			, wrapperType = wrapper.attr('id')
			, template
		;
		
		switch (wrapperType){
			
			case "tr-frame-wrapper": 
				template = _TEMPLATES.FRAME;
				wrapper.append($(template));
				break;
				
			case "tr-spawn-wrapper": 
				openWindow4Spawn();
				break;
		}
	}
	
	function openWindow4Spawn(){
		
		if ($.trim(_$name.val()) == ""){
			
			_$msg.text('Elije un nombre para la acción.');
			return false;
		}
		
		_isSpawn = true;
		_spawnName = _$name.val();
		$('#tr-event-type').hide();
		$('#tr-state').hide();
		_$name.val('');
		_$type.select(0);
		_changeType();
		$('#action-type-list').find('li').last().hide();
	}
	
	function closeWindow4Spawn(){
		
		_isSpawn = false;
		$('#tr-event-type').show();
		$('#tr-state').show();
		_$name.val( _spawnName );
		$('#action-type-list').find('li').last().show();
		_$type.select(function(dataItem) {
		    return dataItem.text === "DDSpawn"
		});
		_changeType();
	}
	
	function _removeSpawn(e){
		
		var e = $(e).siblings('input').val();
		delete actionController.spawnContainer[sceneList.selected().id][_$name.val()][e];
	}
	
	function _createSpawnInput(p_name){
		
		var name = p_name || _$name.val();
		
		var template = _TEMPLATES.SPAWN;
		$('#tr-spawn-wrapper').append($(template));
		$('#tr-spawn-wrapper').find('input').last().val( name );
	}
	
	function _reset(){
		
		var leaf = leftTree.selected();
		
		if(leaf){
			
			_objectDataSource.data(leftTree.getObjects());
			
			_$name.val('');
			stateController.reset();
			
			if(leaf.sequences){
				if(leaf.sequences[_idSq].actions.length > 0){
					
					_$event.select(function(dataItem) {
					    return dataItem.text === leaf.sequences[_idSq].actions[0].action.event;
					});
					
					_$event.enable(false);
					stateController.enable(false);
				}else{
					
					_$event.select(0);
					
					_$event.enable(true);
					stateController.enable(true);
				}
			}
			
			_$type.select(0);
			
			$('#tr-duration').show();
			$('#tr-repeat').show();
			_$duration.value(0);
			
			$('#tr-sound').show();
			_$soundTitle.text('');
			
			_$repeat.value(0);
			
			_$.find('.action-param').hide();
			$("#tr-move-x").show();
			$("#tr-move-y").show();
			_$moveX.value(0);
			_$moveY.value(0);
			_$msg.text('');
			
			//Resetear todos los elementos dinámicos
			$('#tr-frame-wrapper').children().each(function(i, e){
				
				if (i == 0){
					$(e).find('.frame-action').val('')
				}
				else {
					$(e).remove();
				}
			})
			$('#tr-spawn-wrapper').children().each(function(i, e){
				
				if (i == 0){
					$(e).find('.spawn-action').val('')
				}
				else {
					$(e).remove();
				}
			})
			
		}
		
	}
	
	function _openWindow(p_idSq){
		
		_idSq = p_idSq;
		
		_reset();

		_$.data("kendoWindow").center().open();
	}
	
	function _openEditWindow(p_idSq, action, actionID){
		
		_editAction = actionID;
		
		_idSq = p_idSq;
		
		//Rellenar el formulario con los datos de la acción que se edita
		_$name.val( action.name );
		stateController.setValue( action.state );
		
		//Deshabilitamos los combos de evento y estado. 
		_$event.select(function(dataItem) {
		    return dataItem.text === action.event
		});
		
		_$event.enable(false);
		stateController.enable(false);
			
		_$type.select(function(dataItem) {
		    return dataItem.text === action.type
		});
		
		_$duration.value( action.duration );
		
		_$soundTitle.text( action.fx );
		
		_$repeat.value( action.repeat );
		
		_changeType();
		
		//Rellenar parámetros propios de cada tipo
		var type = _$type.value();
		
		if (type == "DDMoveTo" || type == "DDMoveBy"){
			_$moveX.value(action.cfg1);
			_$moveY.value(action.cfg11);
		}
		else if (type == "DDRotateTo" || type == "DDRotateBy"){
			_$angle.value(action.cfg1);
		}
		else if (type == "DDScaleTo" || type == "DDScaleBy"){
			_$scaleX.value(action.cfg1 / deviceController.canvasRatio);
			_$scaleY.value(action.cfg11 / deviceController.canvasRatio);
		}
		else if (type == "DDTextureChange"){
			_$texture.val(action.cfg1);
		}
		else if (type == "DDPlayActionToBo"){
			_$toboObject.value(action.cfg1);
			_$toboAction.val(action.cfg11);
		}
		else if (type == "DDEnableBo"){
			_$enableToboObject.value(action.cfg1);
			$("[name='enable-tobo-action']").each(function(i,e){
				var value = $(this).val(); 
				$(this).attr('checked', $(this).val() == action.cfg11)
			})
		}
		else if (type == "DDLaunchScene"){
			_$launchScene.val(action.cfg1);
		}
		else if (type == "DDEnableBGMusic"){
			$("[name='enable-tobo-action']").each(function(i,e){
				var value = $(this).val(); 
				$(this).attr('checked', $(this).val() == action.cfg1)
			})
		}
		else if (type == "DDChangeBGMusic"){
			_$changeMusicTitle.text(action.cfg1);
		}
		else if (type == "DDStopAction"){
			_$stopObject.value(action.cfg1);
			_$stopAction.val(action.cfg11);
		}
		else if (type == "DDDropEnd"){
			_$dropObject.value(action.cfg1);
			_$dropAction.val(action.cfg11);
		}
		else if (type == "DDHighlight"){
			_$highlightObject.value(action.cfg1);
			_$highlightAction.val(action.cfg11);
		}
		else if (type == "DDIndexChange"){
			_$indexChange.value(action.cfg1);
		}
		else if (type == "DDStateChange"){
			_$stateChange.val(action.cfg1);
		}
		else if (type == "DDPlayCustomAction"){
			_$playAction.val(action.cfg1);
		}
		else if (type == "DDFrameAction"){
			
			var   wrapper = $('#tr-frame-wrapper')
				, firstElem = wrapper.find('.frame-action').first()
			;
			
			//Resetear todos los elementos dinámicos
			$('#tr-frame-wrapper').children().each(function(i, e){
				
				if (i != 0){
					$(e).remove();
				}
			})
			
			//Setear parámetro obligatorio
			firstElem.val( action.cfg1 );
			
			//Crear y setear posibles parámetros opcionales
			var index = 2;
			var exit = false;
			var template = _TEMPLATES.FRAME;
			while (!exit){
				
				if (action.hasOwnProperty('cfg' + index)){
					
					wrapper.append($(template));
					wrapper.find('.frame-action').last().val( action['cfg'+index])
					++index;
				}
				else {
					exit = true;
				}
			}
			
		}
		else if (type == "DDSpawn"){
			
			var   wrapper = $('#tr-spawn-wrapper')
				, firstElem = wrapper.find('.spawn-action').first()
			;
			
			//Eliminar inputs anteriores
			$('#tr-spawn-wrapper').children().each(function(i, e){
				
				if (i != 0){
					$(e).remove();
				}
			})
			
			//Crear nuevos inputs
			if (action.cfg1){
				$.each(action.cfg1, function(i,e){
					
					_createSpawnInput(i);
				})
			}
		}
		
		_$.data("kendoWindow").center().open();
	}
	
	function _closeWindow(){
		
		_editAction = false;
		
		_$.data("kendoWindow").close();
	}
	
	function _changeType(){
		
		//reset
		_$.find('.action-param').hide();
		/*
		_$.find('.action-param input[type=text]').val('');
		_$.find('.action-param input[data-role=numerictextbox]').each(function(){
			$(this).data("kendoNumericTextBox").value(0);
		});
		*/

		_$msg.text('');
		
		var type = _$type.value();
		
		var noDuration = (  type == "DDPlayActionToBo" || type == "DDTextureChange" || type == "DDEnableBo" ||
							type == "DDLaunchScene" || type == "DDLaunchNextScene" || type == "DDLaunchPrevScene" ||
							type == "DDEnableBGMusic" || type == "DDChangeBGMusic" || type == "DDStopAction" ||
							type == "DDDropEnd" || type == "DDHighlight" || type == "DDIndexChange" ||
							type == "DDStateChange" || type == "DDPlayCustomAction" || type == "DDIndexChange" ||
							type == "DDRepeatForever" || type == "DDVibrate" || type == "DDSpawn");
		
		var noSound = ( type == "DDPlayActionToBo" || type == "DDTextureChange" || type == "DDEnableBo" ||
						type == "DDLaunchScene" || type == "DDLaunchNextScene" || type == "DDLaunchPrevScene" ||
						type == "DDEnableBGMusic" || type == "DDChangeBGMusic" || type == "DDStopAction" ||
						type == "DDDropEnd" || type == "DDHighlight" || type == "DDIndexChange" ||
						type == "DDStateChange" || type == "DDPlayCustomAction" || type == "DDIndexChange" ||
						type == "DDRepeat" || type == "DDRepeatForever" || type == "DDDelay" || type == "DDVibrate" ||
						type == "DDSpawn" );
		
		
		$('#tr-duration').toggle( !noDuration );
		$('#tr-repeat').toggle( !noDuration && type != "DDDelay"  );
		$('#tr-sound').toggle( !noSound );
		
		if (type == "DDMoveTo" || type == "DDMoveBy"){
			$("#tr-move-x").show();
			$("#tr-move-y").show();
		}
		else if (type == "DDRotateTo" || type == "DDRotateBy"){
			$("#tr-rotate").show();
		}
		else if (type == "DDScaleTo" || type == "DDScaleBy"){
			$("#tr-scale-x").show();
			$("#tr-scale-y").show();
		}
		else if (type == "DDTextureChange"){
			$("#tr-texture").show();
		}
		else if (type == "DDPlayActionToBo"){
			$("#tr-tobo-object").show();
			$("#tr-tobo-action").show();
		}
		else if (type == "DDEnableBo"){
			$("#tr-enable-tobo-object").show();
			$("#tr-enable-tobo-boolean").show();
		}
		else if (type == "DDLaunchScene"){
			$("#tr-launch-scene").show();
		}
		else if (type == "DDEnableBGMusic"){
			$("#tr-enable-music").show();
		}
		else if (type == "DDChangeBGMusic"){
			$("#tr-change-music").show();
		}
		else if (type == "DDStopAction"){
			$("#tr-stop-object").show();
			$("#tr-stop-action").show();
		}
		else if (type == "DDDropEnd"){
			$("#tr-drop-object").show();
			$("#tr-drop-action").show();
		}
		else if (type == "DDHighlight"){
			$("#tr-highlight-object").show();
			$("#tr-highlight-action").show();
		}
		else if (type == "DDIndexChange"){
			$("#tr-index-change").show();
		}
		else if (type == "DDStateChange"){
			$("#tr-state-change").show();
		}
		else if (type == "DDPlayCustomAction"){
			$("#tr-play-action").show();
		}
		else if (type == "DDFrameAction"){
			$("#tr-frame-action").show();
		}
		else if (type == "DDSpawn"){
			$("#tr-spawn-action").show();
		}

	}

	
	function _check(){
		
		var repeated = true;
		
		if ($.trim(_$name.val()) == ""){
			
			_$msg.text('Elije un nombre para la acción.');
			return false;
		}
		
		if ( _$repeat.value() != 0 && _$duration.value() == 0){
			
			_$msg.text('Indica una duración para repetir la acción.');
			return false;
		}
		
		
		var actionEvent = _$event.value();
		var actionState = stateController.getValue();
		
		$.each(leftTree.selected().sequences, function(i,e){

			if (_idSq != e.idSq && e.actions && e.actions.length && 
				e.actions[0].action.event == actionEvent && e.actions[0].action.state == actionState){
					
				_$msg.text('Ya existe otra secuencia para ese par evento - estado.');
				repeated = false;
			}
			
		})
		
		return repeated;
	}

	
	function _addAction(){
		
		var actionName = $.trim(_$name.val());
		var actionEvent = _$event.value();
		var actionState = stateController.getValue();
		
		//create a new action in the selected leaf 
		var type = _$type.value();
		var newAction = {
			  event: actionEvent
			, name: actionName
			, state: actionState
			, type: _$type.value()
			, repeat: _$repeat.value()
		}
		
		if (type != "DDPlayActionToBo" && type != "DDSpawn"){
			
			$.extend(newAction, {
				  duration: _$duration.value()
				, fx: $.trim(_$soundTitle.text())
			});
		}
		
		if (type == "DDMoveTo" || type == "DDMoveBy"){
			newAction.cfg1 = _$moveX.value();
			newAction.cfg11 = _$moveY.value();
		}
		else if (type == "DDRotateTo" || type == "DDRotateBy"){
			newAction.cfg1 = _$angle.value();
		}
		else if (type == "DDScaleTo" || type == "DDScaleBy"){
			newAction.cfg1 = _$scaleX.value() * deviceController.canvasRatio;
			newAction.cfg11 = _$scaleY.value() * deviceController.canvasRatio;
		}
		else if (type == "DDTextureChange"){
			newAction.cfg1 = _$texture.val();
		}
		else if (type == "DDPlayActionToBo"){
			newAction.cfg1 = _$toboObject.value();
			newAction.cfg11 = _$toboAction.val();
		}
		else if (type == "DDEnableBo"){
			newAction.cfg1  = _$enableToboObject.value();
			newAction.cfg11 = $('input:radio[name=enable-tobo-action]:checked').val();
		}
		else if (type == "DDLaunchScene"){
			newAction.cfg1 = _$launchScene.val();
		}
		else if (type == "DDLaunchNextScene"){
			newAction.cfg1 = sceneList.getNextScene();
		}
		else if (type == "DDLaunchPrevScene"){
			newAction.cfg1 = sceneList.getPrevScene();
		}
		else if (type == "DDEnableBGMusic"){
			newAction.cfg1 = $('input:radio[name=enable-music]:checked').val();
		}
		else if (type == "DDChangeBGMusic"){
			newAction.cfg1 = _$changeMusicTitle.text();
		}
		else if (type == "DDStopAction"){
			newAction.cfg1 = _$stopObject.value();
			newAction.cfg11 = _$stopAction.val();
		}
		else if (type == "DDDropEnd"){
			newAction.cfg1 = _$dropObject.value();
			newAction.cfg11 = _$dropAction.val();
		}
		else if (type == "DDHighlight"){
			newAction.cfg1 = _$highlightObject.value();
			newAction.cfg11 = _$highlightAction.val();
		}
		else if (type == "DDIndexChange"){
			newAction.cfg1 = _$indexChange.value();
		}
		else if (type == "DDStateChange"){
			newAction.cfg1 = _$stateChange.val();
		}
		else if (type == "DDPlayCustomAction"){
			newAction.cfg1 = _$playAction.val();
		}
		else if (type == "DDFrameAction"){
			//newAction.cfg1 = _$frameAction.val();
			$('#tr-frame-wrapper').find('.frame-action').each(function(i, e){
				
				newAction['cfg' + (i+1)] = $(e).val();
			})
		}
		else if (type == "DDSpawn"){
			
			newAction.cfg1 = actionController.spawnContainer[sceneList.selected().id][_$name.val()]
		}
		
		
		
		if (_isSpawn){
			
			actionController.spawnContainer[sceneList.selected().id] = actionController.spawnContainer[sceneList.selected().id] || {};
			actionController.spawnContainer[sceneList.selected().id][_spawnName] = actionController.spawnContainer[sceneList.selected().id][_spawnName] || {};
			actionController.spawnContainer[sceneList.selected().id][_spawnName][_$name.val()] = newAction;
			
			_createSpawnInput();
			
			closeWindow4Spawn();
		}
		else {
		
			var leaf = leftTree.selected();
			if (leaf){
			
				//TOREV: eliminar leaf.actions. No se debe usar nunca, ha evolucionado en leaf.sequences
				//Se sigue usando en el timeline y no debería
				if (!leaf.actions){
					leaf.actions = {}
				}
			
				leaf.actions[actionName] = newAction;
				
				if (_editAction){
					
					timeline.AddEditedAction(_idSq, actionName, (type != "DDPlayActionToBo") ? newAction.duration : 0, _editAction);
				}
				else {
					
					timeline.AddAction(_idSq, actionName, (type != "DDPlayActionToBo") ? newAction.duration : 0);	
				}
				
			}
			else {
				console.log('Error al crear la acción. No hay ningún objeto seleccionado.')
			}
			_closeWindow();
		}
		
			
		
	}
	
	
	this.openWindow = _openWindow;
	this.init =  _init;
	this.openEditWindow = _openEditWindow;
}